package com.yaodian100.ec.image.service.impl;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;

import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.service.BaseManager;
import com.yaodian100.core.common.service.impl.DomainServiceImpl;
import com.yaodian100.core.common.utils.ImageUtils;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.ec.image.entity.Image;
import com.yaodian100.ec.image.entity.Image.IMG_TYPE;
import com.yaodian100.ec.image.service.Image2Service;
import com.yaodian100.ec.product.entity.Product;
import com.yaodian100.ec.product.entity.SpecificationMajor;
import com.yaodian100.ec.proposeproduct.service.ProposeProductService;

public class Image2ServiceImpl extends DomainServiceImpl<Image> implements Image2Service {
	@Autowired
	private ProposeProductService proposeProductService;
	@Autowired
	private BaseManager baseMgr;
	@Autowired
	private JdbcTemplate jdbcTemplate;

	final String imgFolder = "PImg";

	@Override
	@Transactional(readOnly = false)
	public void deletePic(Long[] picIds) {
		if (null != picIds && picIds.length > 0) {
			try {
				List<Image> images = null;
				List<Image> delImages = new ArrayList<Image>();
				CommonCriteria criteria = null;
				File imageFile = null;
				Image image = null;
				for (int i = 0; i < picIds.length; i++) {
					image = getDao().get(picIds[i]);
					if (null != image) {
						if (IMG_TYPE.IMGB.getValue().equalsIgnoreCase(image.getType())) {
							criteria = new CommonCriteria();
							criteria
									.addRlike("imgFilePath", image.getImgFilePath().substring(0, image.getImgFilePath().length() - 5));
							images = getDao().getList(criteria, null);
							if (null != images && images.size() > 0) {
								for (Image imagebs : images) {
									// imagebs.setIsDelete("Y");
									delImages.add(imagebs);
									imageFile = new File(ServerValue.getMidApachePath() + image.getImgFilePath());
									if (imageFile.exists()) {
										imageFile.delete();
									}
								}
							}
						} else {
							// image.setIsDelete("Y");
							delImages.add(image);
							imageFile = new File(ServerValue.getMidApachePath() + image.getImgFilePath());
							if (imageFile.exists()) {
								imageFile.delete();
							}
							// 刪除spec
							Object[] objs = baseMgr.queryByHql("from Image where parentId = ?", new Object[] { image.getId() });
							if (null != objs) {
								for (Object obj : objs) {
									Image specImg = (Image) obj;
									delImages.add(image);
									imageFile = new File(ServerValue.getMidApachePath() + specImg.getImgFilePath());
									if (imageFile.exists()) {
										imageFile.delete();
									}
								}
							}
						}
					}
				}
				if (!delImages.isEmpty() && delImages.size() > 0) {
					getDao().deleteBatch(delImages);
				}
			} catch (Exception e) {
				logger.info("deletePic error:{}" + e);

			}
		}
	}

	/**
	 * 长形图/方形图 resize
	 * 
	 * @param productId
	 * @param type
	 * @return
	 * @throws CoreException
	 */
	@Transactional(readOnly = false)
	boolean resizeCoverImg(Image image) throws CoreException {
		File f = null;
		InputStream inputStream = null;
		BufferedImage bufferedImage = null;
		ImageUtils imageUtils = new ImageUtils();
		StringBuffer imageFilePath = new StringBuffer(ServerValue.getMidApachePath()).append("PImg").append(File.separator);
		String baseImgPath = "/PImg/" + image.getProductId().substring(0, 4) + "/" + image.getProductId() + "/"
				+ image.getProductId();
		List<Image> addImageList = new ArrayList<Image>();
		Image newImage = null;
		try {
			f = new File(ServerValue.getMidApachePath() + StringUtils.substring(image.getImgFilePath(), 1));
			if (f.exists()) {
				inputStream = new FileInputStream(f);
				bufferedImage = ImageIO.read(inputStream);
				inputStream.close();
				if (null == bufferedImage) {
					throw new CoreException("无法载入图檔");
				}
				if (StringUtils.equals(IMG_TYPE.MAIN.getValue(), image.getType())) {
					// 先刪除已存在的方形封面图
					baseMgr.executeHql("delete from Image where productId = ? and type = ? and mainSpecId is null", new Object[] {
							image.getProductId(), IMG_TYPE.MAIN.getValue() });
					// resize
					imageUtils.mainResize2(image.getProductId(), bufferedImage, "jpg", imageFilePath.toString());
					List<String> mainImgSize = Arrays.asList("_m500.jpg", "_m250.jpg", "_m135.jpg", "_m100.jpg", "_m75.jpg",
							"_m50.jpg");
					for (int i = 0; i < mainImgSize.size(); i++) {
						newImage = createImage(image.getProductId(), IMG_TYPE.MAIN.getValue(), baseImgPath + mainImgSize.get(i),
								i + 1, null, "", null);
						addImageList.add(newImage);
					}
				}
				if (StringUtils.equals(IMG_TYPE.RMAIN.getValue(), image.getType())) {
					// 先刪除已存在的长形封面图
					baseMgr.executeHql("delete from Image where productId = ? and type = ? and mainSpecId is null", new Object[] {
							image.getProductId(), IMG_TYPE.RMAIN.getValue() });
					// resize
					imageUtils.rmainResize(image.getProductId(), bufferedImage, "jpg", imageFilePath.toString());

					List<String> rmainImgSize = Arrays.asList("_rm530.jpg", "_rm330.jpg", "_rm225.jpg", "_rm180.jpg",
							"_rm130.jpg", "_rm93.jpg");
					for (int i = 0; i < rmainImgSize.size(); i++) {
						newImage = createImage(image.getProductId(), IMG_TYPE.RMAIN.getValue(), baseImgPath + rmainImgSize.get(i),
								i + 1, null, "", null);
						addImageList.add(newImage);
					}
				}
				if (!addImageList.isEmpty() && addImageList.size() > 0) {
					getDao().saveOrUpdateBatch(addImageList);
				}
			}// else {
			// throw new CoreException("檔案不存在");
			// }
		} catch (Exception e) {
			throw new CoreException(e.toString());
		}
		imageFilePath.setLength(0);
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.image.service.Image2Service#changeCover(java.lang.String, java.lang.Long)
	 */
	@Override
	@Transactional(readOnly = false)
	public boolean changeCover(String productId, Long mainSpecId) throws CoreException {
		Object[] images = baseMgr.queryByHql(
				"from Image where productId = ? and mainSpecId = ? and type in ('RMAIN','MAIN') and showSeq = 1 ",
				new Object[] { productId, mainSpecId });
		if (null != images && images.length > 0) {
			Image image = null;
			for (Object imgObj : images) {
				image = (Image) imgObj;
				if ("m500".equals(image.getPicDesc()) || image.getType().equals("RMAIN")) {
					resizeCoverImg(image);
				}
			}
			// logger.info("mainSpecId:{}", mainSpecId);
			// 更新major 将封面设为Y (1)先将全部的major设为N (2)将设为封面的major设为Y
			Product product = (Product) baseMgr.get(Product.class, productId);
			if (null != product && product.getProductType() != 6) {// 非n選m商品
				// jdbcTemplate.update("update ec_specification_major set is_cover = 'N' where product_id = '" + productId +
				// "'");
				// logger.info("(1)先将全部的major设为N");
				baseMgr.executeHql("update SpecificationMajor set isCover = 'N' where productId = ? ",
						new Object[] { productId });
				getDao().flush();
			}
			// jdbcTemplate.update("update ec_specification_major set is_cover = 'Y' where main_spec_id = '" + mainSpecId +
			// "'");
			// baseMgr.executeHql("update SpecificationMajor set isCover = 'Y' where mainSpecId = ? ",
			// new Object[] { mainSpecId });
			// logger.info("(2)将设为封面的major设为Y");
			SpecificationMajor major = (SpecificationMajor) baseMgr.get(SpecificationMajor.class, mainSpecId);
			major.setIsCover("Y");
			baseMgr.update(major);
			getDao().flush();
		}
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.image.service.ImageService#uploadImage(java.lang.String, java.lang.String, java.lang.String,
	 * java.io.File[], java.lang.String[])
	 */
	@Transactional(readOnly = false)
	public boolean uploadImage(String productId, List<String> type, List<String> specId, List<File> images,
			List<String> imageFileName) throws CoreException {
		return uploadImage(productId, type, specId, images, imageFileName, "", null, null, null);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.image.service.ImageService#uploadImage(java.lang.String, java.lang.String, java.lang.String,
	 * java.io.File[], java.lang.String[])
	 */
	@Transactional(readOnly = false)
	public boolean uploadImage(String productId, List<String> type, List<String> specId, List<File> images,
			List<String> imageFileName, String coverId) throws CoreException {
		return uploadImage(productId, type, specId, images, imageFileName, coverId, null, null, null);
	}

	Long getMaxShowSeq(String productId, Long mainSpecId) {
		Long maxSeq = 0l;
		Object[] maxShowSeq = baseMgr.queryByHql("select max(showSeq) from Image where productId = ? and mainSpecId = ?",
				new Object[] { productId, mainSpecId });
		if (null != maxShowSeq) {
			maxSeq = Long.parseLong(maxShowSeq[0].toString() + 1);
		}
		return maxSeq;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.image.service.ImageService#uploadImage(java.lang.String, java.lang.String, java.lang.String,
	 * java.io.File[], java.lang.String[])
	 */
	@Transactional(readOnly = false)
	public boolean uploadImage(String productId, List<String> type, List<String> specId, List<File> images,
			List<String> imageFileName, String coverId, Long[] delSpecImgIds, Map<Long, File> replaceImgFiles,
			Map<String, Integer> imgShowSeqData) throws CoreException {
		try {
			Product product = (Product) baseMgr.get(Product.class, productId);
			// // 找出目前的封面图
			// String nowCoverId = "";
			Object[] objImgs = baseMgr.queryByHql("from SpecificationMajor where productId = ? and isDelete = 'N'",
					new Object[] { productId });
			Map<Long, String> coverMap = new HashMap<Long, String>();
			SpecificationMajor major = null;
			if (null != objImgs && objImgs.length > 0) {
				for (Object obj : objImgs) {
					major = (SpecificationMajor) obj;
					if (null != major) {
						coverMap.put(major.getMainSpecId(), major.getIsCover());
					}
				}
			}
			String tempMain = null;
			String tempMainSubName = null;
			String tempSpec = null;
			String tempSpecSubName = null;

			if (product.getGraphicType().equals("S")) {
				tempMain = IMG_TYPE.MAIN.getValue();
				tempSpec = IMG_TYPE.MSPEC.getValue();
				// tempMainSubName = "_m400.jpg";
				tempMainSubName = "_m500.jpg";
				tempSpecSubName = "s75";
			} else {
				tempMain = IMG_TYPE.RMAIN.getValue();
				tempSpec = IMG_TYPE.RMSPEC.getValue();
				tempMainSubName = "_rm530.jpg";
				tempSpecSubName = "rs99";
			}
			createProdImgFolder(productId);
			StringBuffer fullImgfilePath = new StringBuffer();
			fullImgfilePath.append(ServerValue.getMidApachePath()).append("PImg").append(File.separator).append(
					productId.substring(0, 4)).append(File.separator).append(productId).append(File.separator).append(productId);

			StringBuffer imgFilePath = new StringBuffer();
			imgFilePath.append(ServerValue.getMidApachePath()).append("PImg").append(File.separator);

			String baseImgPath = "/PImg/" + productId.substring(0, 4) + "/" + productId + "/" + productId;
			Image image = null;
			Image parentImage = null;
			File f = null;
			InputStream inputStream = null;
			BufferedImage bufferedImage = null;
			ImageUtils imageUtils = new ImageUtils();
			List<Image> addImageList = new ArrayList<Image>();
			int maxShowSeq = 0;
			Map<String, Integer> mainShowSeq = new HashMap<String, Integer>();
			Map<String, Integer> rmainShowSeq = new HashMap<String, Integer>();
			String dbFilePath = "";
			String imgType = "";
			int showSeq = 0;
			Long mainSpecId = null;

			// 删除图檔
			if (null != delSpecImgIds) {
				logger.info("删除图檔");
				deletePic(delSpecImgIds);
			}

			// 替換檔案
			if (null != replaceImgFiles && !replaceImgFiles.isEmpty() && replaceImgFiles.size() > 0) {
				logger.info("替換檔案");
				replaceMainAndSpecFile(replaceImgFiles);
			}

			for (int i = 0; i < type.size(); i++) {
				// 上传主規格方形圖
				if (StringUtils.equalsIgnoreCase(IMG_TYPE.MAIN.getValue(), type.get(i))) {
					logger.info("MAIN...........");
					if (mainShowSeq.isEmpty() && mainShowSeq.size() == 0 || null == mainShowSeq.get(specId.get(i))) {
						mainShowSeq.put(specId.get(i), 1);
					} else {
						mainShowSeq.put(specId.get(i), mainShowSeq.get(specId.get(i)) + 1);
					}
					imgType = IMG_TYPE.MAIN.getValue();
					showSeq = mainShowSeq.get(specId.get(i));
					mainSpecId = Long.parseLong(specId.get(i));
					dbFilePath = baseImgPath + "_" + specId.get(i) + "_" + showSeq + "_m500.jpg";

					deleteImgData(productId, imgType, mainSpecId.toString(), showSeq);
					// 写檔
					f = writeImageFile(fullImgfilePath.toString() + "_" + mainSpecId + "_" + showSeq + "_m500.jpg", images.get(i));
					// 新增至db
					image = createImage(productId, imgType, dbFilePath, showSeq, mainSpecId, "m500", null);
					parentImage = getDao().save(image);

					// check是否为当前封面，是的话就要重新缩图
					if (!coverMap.isEmpty() && coverMap.size() > 0) {
						if (coverMap.containsKey(Long.parseLong(specId.get(i)))
								&& "Y".equals(coverMap.get(Long.parseLong(specId.get(i))))) {
							changeCover(productId, Long.parseLong(specId.get(i)));

						}
					}

					// // 读檔做m400resize
					// bufferedImage = ImageIO.read(f);
					// imageUtils.main400Resize(productId, bufferedImage, "jpg", imgFilePath.toString(), mainSpecId.toString(),
					// showSeq);
					// // 新增至db
					// dbFilePath = baseImgPath + "_" + mainSpecId + "_" + showSeq + "_m400.jpg";
					// image = createImage(productId, imgType, dbFilePath, showSeq, mainSpecId, "m400", null);
					// addImageList.add(image);

					if (product.getProductType() != 6) {
						// resize to icon
						if (showSeq == 1) {
							imgType = IMG_TYPE.ICON.getValue();
							dbFilePath = baseImgPath + "_" + specId.get(i) + "_i40.jpg";
							deleteImgData(productId, imgType, mainSpecId.toString(), showSeq);
							bufferedImage = ImageIO.read(f);
							imageUtils.iconResize(productId, bufferedImage, "jpg", imgFilePath.toString(), mainSpecId.toString());
							image = createImage(productId, imgType, dbFilePath, 1, mainSpecId, "", null);
							addImageList.add(image);
						}
					}

					// resize to spec
					imgType = IMG_TYPE.MSPEC.getValue();
					dbFilePath = baseImgPath + "_" + specId.get(i) + "_" + showSeq + "_s75.jpg";
					deleteImgData(productId, imgType, mainSpecId.toString(), showSeq);
					bufferedImage = ImageIO.read(f);
					imageUtils.specResize(productId, bufferedImage, "jpg", imgFilePath.toString(), specId.get(i), "s75", showSeq);
					image = createImage(productId, imgType, dbFilePath, showSeq, mainSpecId, "", parentImage.getId());
					addImageList.add(image);
				}
				if (StringUtils.equalsIgnoreCase(IMG_TYPE.RMAIN.getValue(), type.get(i))) {
					logger.info("RMAIN...........");
					if (rmainShowSeq.isEmpty() && rmainShowSeq.size() == 0 || null == rmainShowSeq.get(specId.get(i))) {
						rmainShowSeq.put(specId.get(i), 1);
					} else {
						rmainShowSeq.put(specId.get(i), rmainShowSeq.get(specId.get(i)) + 1);
					}

					imgType = IMG_TYPE.RMAIN.getValue();
					showSeq = rmainShowSeq.get(specId.get(i));
					mainSpecId = Long.parseLong(specId.get(i));
					dbFilePath = baseImgPath + "_" + mainSpecId + "_" + showSeq + "_rm530.jpg";

					deleteImgData(productId, imgType, mainSpecId.toString(), showSeq);
					// 写檔
					f = writeImageFile(fullImgfilePath.toString() + "_" + mainSpecId + "_" + showSeq + "_rm530.jpg", images
							.get(i));
					// 新增至db
					image = createImage(productId, imgType, dbFilePath, showSeq, mainSpecId, "", null);
					parentImage = getDao().save(image);

					// resize to spec
					imgType = IMG_TYPE.RMSPEC.getValue();
					dbFilePath = baseImgPath + "_" + mainSpecId + "_" + showSeq + "_rs99.jpg";
					deleteImgData(productId, IMG_TYPE.RMSPEC.getValue(), mainSpecId.toString(), showSeq);
					bufferedImage = ImageIO.read(f);
					imageUtils.specResize(productId, bufferedImage, "jpg", imgFilePath.toString(), mainSpecId.toString(), "rs99",
							showSeq);
					image = createImage(productId, imgType, dbFilePath, showSeq, mainSpecId, "", parentImage.getId());
					addImageList.add(image);

					// check是否为当前封面，是的话就要重新缩图
					if (!coverMap.isEmpty() && coverMap.size() > 0) {
						if (coverMap.containsKey(Long.parseLong(specId.get(i)))
								&& "Y".equals(coverMap.get(Long.parseLong(specId.get(i))))) {
							changeCover(productId, Long.parseLong(specId.get(i)));

						}
					}
				}
				// 上传说明檔
				if (StringUtils.equalsIgnoreCase(IMG_TYPE.DESC.getValue(), type.get(i))) {
					logger.info("DESC...........");
					StringBuilder sbNameMapKey = new StringBuilder();
					StringBuilder sbNameMapValue = new StringBuilder();
					Map<String, String> replaceNameMap = new HashMap<String, String>();
					List<String> replaceMapKeyList = new ArrayList<String>();
					String timeflag = StringUtils.leftPad(((BigDecimal) getDao().getSQLQueryByList(
							"select seq_image_name.nextval from dual", null, 0, -1).get(0)).toString(), 13, "0");
					inputStream = new FileInputStream(images.get(i));
					bufferedImage = ImageIO.read(inputStream);
					inputStream.close();
					imageUtils.descResize(productId, bufferedImage, "d" + timeflag, "jpg", imgFilePath.toString());
					imgType = IMG_TYPE.DESC.getValue();
					showSeq = i + 1;
					mainSpecId = null;
					dbFilePath = baseImgPath + "_d" + timeflag + "." + "jpg";
					image = createImage(productId, imgType, dbFilePath, showSeq, null, "", null);
					addImageList.add(image);
					if (product.getProductType() != 6) {// 略过nm
						if (null != imageFileName) {
							// 置换图档名
							sbNameMapKey.setLength(0);
							sbNameMapValue.setLength(0);
							sbNameMapKey.append(productId).append("_d").append(timeflag).append(".jpg");
							sbNameMapValue.append(imageFileName.get(i)).append(",").append(productId);
							replaceNameMap.put(sbNameMapKey.toString(), sbNameMapValue.toString());
							replaceMapKeyList.add(sbNameMapKey.toString());
						}
						// 開始置換HTML的圖檔名稱
						if (MapUtils.isNotEmpty(replaceNameMap)) {
							proposeProductService.replaceImageName(replaceNameMap, replaceMapKeyList);
						}
					}
				}

				// 上传商品图
				if (StringUtils.equalsIgnoreCase(IMG_TYPE.PRDT.getValue(), type.get(i))) {
					logger.info("PRDT...........");
					String timeflag = StringUtils.leftPad(((BigDecimal) getDao().getSQLQueryByList(
							"select seq_image_name.nextval from dual", null, 0, -1).get(0)).toString(), 13, "0");
					inputStream = new FileInputStream(images.get(i));
					bufferedImage = ImageIO.read(inputStream);
					inputStream.close();
					imageUtils.prdtResize(productId, bufferedImage, timeflag, "jpg", imgFilePath.toString());

					showSeq = i + 1;
					dbFilePath = baseImgPath + "_" + timeflag + "_b" + "." + "jpg";
					image = createImage(productId, IMG_TYPE.IMGB.getValue(), dbFilePath, showSeq, null, "", null);
					addImageList.add(image);

					dbFilePath = baseImgPath + "_" + timeflag + "_s" + "." + "jpg";
					image = createImage(productId, IMG_TYPE.IMGS.getValue(), dbFilePath, showSeq, null, "", null);
					addImageList.add(image);
				}
				if (StringUtils.equalsIgnoreCase("NEWMAIN", type.get(i))) {
					showSeq = imgShowSeqData.get(images.get(i).getName());
					mainSpecId = Long.parseLong(specId.get(i));
					dbFilePath = baseImgPath + "_" + specId.get(i) + "_" + maxShowSeq + tempMainSubName;
					maxShowSeq = getMaxShowSeq(productId, Long.parseLong(specId.get(i))).intValue() + i;

					f = writeImageFile(fullImgfilePath.toString() + "_" + mainSpecId + "_" + maxShowSeq + tempMainSubName, images
							.get(i));

					dbFilePath = baseImgPath + "_" + mainSpecId + "_" + maxShowSeq + tempMainSubName;
					image = createImage(productId, tempMain, dbFilePath, showSeq, mainSpecId, StringUtils.equals("_m500.jpg",
							tempMainSubName) ? "m500" : "", null);
					parentImage = getDao().save(image);

					// resize to spec
					deleteImgData(productId, tempSpec, mainSpecId.toString(), maxShowSeq);
					bufferedImage = ImageIO.read(f);
					imageUtils.specResize(productId, bufferedImage, "jpg", imgFilePath.toString(), mainSpecId.toString(),
							tempSpecSubName, maxShowSeq);
					dbFilePath = baseImgPath + "_" + mainSpecId + "_" + maxShowSeq + "_" + tempSpecSubName + ".jpg";
					image = createImage(productId, tempSpec, dbFilePath, showSeq, mainSpecId, "", parentImage.getId());
					addImageList.add(image);
				}
				// 上傳示意圖
				if (StringUtils.equalsIgnoreCase(IMG_TYPE.ICON.getValue(), type.get(i))) {
					logger.info("ICON...........");
					writeImageFile(fullImgfilePath.toString() + "_" + specId.get(i) + "_i40.jpg", images.get(i));
				}
			}
			if (!addImageList.isEmpty() && addImageList.size() > 0) {
				getDao().saveOrUpdateBatch(addImageList);
			}

			// 设为当前封面
			if (StringUtils.isNotBlank(coverId)) {
				logger.info("设为当前封面");
				changeCover(productId, Long.parseLong(coverId));
			}

			// 重設main showseq
			if (null != imgShowSeqData && !imgShowSeqData.isEmpty() && imgShowSeqData.size() > 0) {
				logger.info("重設main showseq");
				reSetShowSeq(productId, Arrays.asList(tempMain, tempSpec), imgShowSeqData);
			}
			logger.info("更新major图檔路径");
			// 更新major图檔路径
			updMajor(productId);
			// 更新step
			if (product.getProductType() != 6) {// 非n选m商品
				if (product.getStepFlag() == 3) {
					product.setStepFlag(4);
					baseMgr.update(product);
				}
			} else {
				if (product.getStepFlag() == 2) {
					product.setStepFlag(3);
					baseMgr.update(product);
				}
			}
		} catch (Exception e) {
			logger.info("error:{}", e.fillInStackTrace());
			return false;
		}
		getDao().flush();
		return true;
	}

	/**
	 * 异动major
	 * 
	 * @param productId
	 */
	@Transactional(readOnly = false)
	public void updMajor(String productId) {
		Object[] majorObjs = baseMgr.queryByHql("from SpecificationMajor where productId = ?", new Object[] { productId });
		if (null != majorObjs && majorObjs.length > 0) {
			SpecificationMajor major = null;
			CommonCriteria crit = null;
			List<Image> images = null;
			StringBuffer mainSb = new StringBuffer();
			StringBuffer rmainSb = new StringBuffer();
			StringBuffer mspecSb = new StringBuffer();
			StringBuffer rmspecSb = new StringBuffer();
			for (Object majorObj : majorObjs) {
				major = (SpecificationMajor) majorObj;
				crit = new CommonCriteria();
				crit.addEq("productId", major.getProductId());
				crit.addIn("type", Arrays.asList(IMG_TYPE.ICON.getValue(), IMG_TYPE.MAIN.getValue(), IMG_TYPE.RMAIN.getValue(),
						IMG_TYPE.MSPEC.getValue(), IMG_TYPE.RMSPEC.getValue()));
				crit.addEq("mainSpecId", major.getMainSpecId());
				crit.addEq("isDelete", "N");
				images = getDao().getList(crit, new String[] { "showSeq asc" });
				if (null != images && !images.isEmpty() && images.size() > 0) {
					for (Image image : images) {
						if (IMG_TYPE.ICON.getValue().equals(image.getType())) {
							major.setImgIcon(image.getImgFilePath());
						}
						if (IMG_TYPE.MAIN.getValue().equals(image.getType()) && "m500".equals(image.getPicDesc())) {
							mainSb.append(image.getImgFilePath()).append(",");
						}
						if (IMG_TYPE.RMAIN.getValue().equals(image.getType())) {
							rmainSb.append(image.getImgFilePath()).append(",");
						}
						if (IMG_TYPE.MSPEC.getValue().equals(image.getType())) {
							mspecSb.append(image.getImgFilePath()).append(",");
						}
						if (IMG_TYPE.RMSPEC.getValue().equals(image.getType())) {
							rmspecSb.append(image.getImgFilePath()).append(",");
						}
						if (mainSb.length() > 0) {
							major.setImgMain(mainSb.toString().substring(0, mainSb.length() - 1));
						}
						if (rmainSb.length() > 0) {
							major.setImgRmain(rmainSb.toString().substring(0, rmainSb.length() - 1));
						}
						if (mspecSb.length() > 0) {
							major.setImgMspec(mspecSb.toString().substring(0, mspecSb.length() - 1));
						}
						if (rmspecSb.length() > 0) {
							major.setImgRmspec(rmspecSb.toString().substring(0, rmspecSb.length() - 1));
						}
					}
					baseMgr.update(major);
				}
				mainSb.setLength(0);
				rmainSb.setLength(0);
				mspecSb.setLength(0);
				rmspecSb.setLength(0);
			}
		}
	}

	/**
	 * 写檔
	 * 
	 * @param filePath
	 * @param file
	 * @return
	 */
	File writeImageFile(String filePath, File file) {
		try {
			InputStream inputStream = null;
			OutputStream out = null;
			File f = new File(filePath);
			inputStream = new FileInputStream(file);
			out = new FileOutputStream(f);
			byte buf[] = new byte[1024];
			int len;
			while ((len = inputStream.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
			out.close();
			inputStream.close();
			return f;
		} catch (FileNotFoundException e) {
			return null;
		} catch (IOException e) {
			return null;
		}
	}

	/**
	 * 重设主檔图&规格细节图showSeq
	 * 
	 * @param productId
	 * @param types
	 * @param imgShowSeqData
	 */
	void reSetShowSeq(String productId, List<String> types, Map<String, Integer> imgShowSeqData) {
		List<Image> addImageList = null;
		CommonCriteria crit = new CommonCriteria();
		crit.addEq("productId", productId);
		crit.addIn("type", types);
		crit.addEq("isDelete", "N");
		crit.addNe("showSeq", 1);
		List<Image> updImages = getDao().getList(crit, new String[] { "showSeq asc" });
		if (null != updImages) {
			addImageList = new ArrayList<Image>();
			for (Image img : updImages) {
				if (imgShowSeqData.containsKey(img.getId().toString())) {
					img.setShowSeq(imgShowSeqData.get(img.getId().toString()));
					addImageList.add(img);
				}
				if (null != img.getParentId() && imgShowSeqData.containsKey(img.getParentId().toString())) {
					img.setShowSeq(imgShowSeqData.get(img.getParentId().toString()));
					addImageList.add(img);
				}
			}
			if (!addImageList.isEmpty() && addImageList.size() > 0) {
				getDao().saveOrUpdateBatch(addImageList);
			}
		}
	}

	/**
	 * 重设主檔图和规格细节图
	 * 
	 * @param replaceImgFiles
	 */
	void replaceMainAndSpecFile(Map<Long, File> replaceImgFiles) {
		Image image = null;
		BufferedImage bufferedImage = null;
		for (Long imgId : replaceImgFiles.keySet()) {
			try {
				Object[] objs = baseMgr.queryByHql("from Image where id = ? or parentId = ?", new Object[] { imgId, imgId });
				if (null != objs) {
					StringBuffer imgFilePath = new StringBuffer();
					imgFilePath.append(ServerValue.getMidApachePath()).append("PImg").append(File.separator);
					for (Object obj : objs) {
						image = (Image) obj;
						deleteSpecMainImg(image);
						if (Arrays.asList(IMG_TYPE.MAIN.getValue(), IMG_TYPE.RMAIN.getValue()).contains(image.getType())) {
							writeImageFile(ServerValue.getMidApachePath() + image.getImgFilePath().substring(1), replaceImgFiles
									.get(imgId));
						}
						if (Arrays.asList(IMG_TYPE.MSPEC.getValue(), IMG_TYPE.RMSPEC.getValue()).contains(image.getType())) {
							// resize spec
							bufferedImage = ImageIO.read(replaceImgFiles.get(imgId));
							ImageUtils.specResize(image.getProductId(), bufferedImage, "jpg", imgFilePath.toString(), image
									.getMainSpecId().toString(), "s75", Integer.parseInt(image.getImgFilePath().split("_")[2]));
						}
					}
				}
			} catch (IOException e) {
				logger.info("replaceMainAndSpecFile exception:{}", e.fillInStackTrace());
			}
		}
	}

	/**
	 * 建立商品图檔资料夹
	 * 
	 * @param productId
	 */
	void createProdImgFolder(String productId) {
		StringBuffer imgMfilePath = new StringBuffer().append(ServerValue.getMidApachePath()).append("PImg").append(
				File.separator);
		File newFourFolder = new File(imgMfilePath.toString() + productId.substring(0, 4));
		if (!newFourFolder.exists()) {
			newFourFolder.mkdir();
		}
		File newFolder = new File(imgMfilePath.toString() + productId.substring(0, 4) + File.separator + productId);
		if (!newFolder.exists()) {
			newFolder.mkdir();
		}
	}

	/**
	 * 刪除規格細節圖
	 * 
	 * @param imgId
	 */
	void deleteSpecMainImg(Image image) {
		if (null != image) {
			File f = null;
			f = new File(ServerValue.getMidApachePath() + image.getImgFilePath().substring(1));
			if (f.exists()) {
				f.delete();
			}
		}
	}

	/**
	 * 删除图檔
	 * 
	 * @param productId
	 * @param type
	 * @param mainSpecId
	 */
	@Transactional(readOnly = false)
	void deleteImgData(String productId, String type, String mainSpecId, Integer showSeq) {
		CommonCriteria crit = new CommonCriteria();
		crit.addEq("productId", productId);
		crit.addEq("type", type);
		if (StringUtils.isNotBlank(mainSpecId)) {
			crit.addEq("mainSpecId", Long.parseLong(mainSpecId));
		}
		if (0 != showSeq) {
			crit.addEq("showSeq", showSeq);
		}
		// if (Arrays.asList(IMG_TYPE.MSPEC.getValue(), IMG_TYPE.RMSPEC.getValue()).contains(type)) {
		// crit.addEq("showSeq", 1);
		// }
		List<Image> imagelist = getDao().getList(crit, null);
		if (null != imagelist && !imagelist.isEmpty() && imagelist.size() > 0) {
			getDao().deleteBatch(imagelist);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.image.service.Image2Service#batchProcessImage(java.lang.String[], java.lang.String[])
	 */
	@Override
	@Transactional(readOnly = false)
	public void batchProcessImage(Long[] delImgIds, Long[] imgIds, Map<Long, File> replaceImgFiles) {
		// 删除图檔
		if (null != delImgIds) {
			deletePic(delImgIds);
		}
		// 替換檔案，重設showseq
		int i = 1;
		List<Image> updImgList = new ArrayList<Image>();
		Image image = null;
		if (null != imgIds && imgIds.length > 0) {
			for (Long id : imgIds) {
				image = getDao().get(id);
				if (null != image) {
					image.setShowSeq(i);
					updImgList.add(image);
					i++;
				}
			}
			getDao().saveOrUpdateBatch(updImgList);
		}
		if (null != replaceImgFiles && !replaceImgFiles.isEmpty() && replaceImgFiles.size() > 0) {
			BufferedImage bufferedImage = null;
			for (Long imgId : replaceImgFiles.keySet()) {
				try {
					image = getDao().get(imgId);
					bufferedImage = ImageIO.read(replaceImgFiles.get(imgId));
					replaceFile(replaceImgFiles.get(imgId).length(), replaceImgFiles.get(imgId), bufferedImage, image);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
					logger.info("ex:{}", e.fillInStackTrace());
				} catch (IOException e) {
					logger.info("ex2:{}", e.fillInStackTrace());
					e.printStackTrace();
				}
			}
		}
	}

	void replaceFile(long fileSize, File file, BufferedImage bufferedImage, Image image) {
		StringBuffer imgMfilePath = new StringBuffer();
		InputStream is = null;
		OutputStream os = null;
		imgMfilePath.append(ServerValue.getMidApachePath()).append("PImg").append(File.separator);
		boolean isPass = true;
		long limitFileSize = 0;
		long thisFileSize = fileSize;
		int limitImgWidth = 0;
		int limitImgHeight = 0;
		int thisImgWidth = bufferedImage.getWidth();
		int thisImgHeight = bufferedImage.getHeight();

		String filePath = image.getImgFilePath();
		int width = 0;
		int height = 0;
		boolean bb = false;
		boolean pressImage = true;
		boolean mainFileSize = true;
		boolean mainImgSize = true;
		String msg = null;
		if (IMG_TYPE.MAIN.getValue().equalsIgnoreCase(image.getType())) {
			String mainFileSizeMsg = "";
			String mainImgSizeMsg = "";
			if (filePath.endsWith("_m50.jpg")) {
				width = ImageUtils.main50ImgWidth;
				height = ImageUtils.main50ImgLen;
				bb = true;
				pressImage = false;
				limitFileSize = 8 * 1024;
				limitImgWidth = 50;
				limitImgHeight = 50;
			} else if (filePath.endsWith("_m75.jpg")) {
				width = ImageUtils.main75ImgWidth;
				height = ImageUtils.main75ImgLen;
				bb = true;
				pressImage = false;
				limitFileSize = 10 * 1024;
				limitImgWidth = 75;
				limitImgHeight = 75;
			} else if (filePath.endsWith("_m100.jpg")) {
				width = ImageUtils.main100ImgWidth;
				height = ImageUtils.main100ImgLen;
				bb = true;
				pressImage = false;
				limitFileSize = 16 * 1024;
				limitImgWidth = 100;
				limitImgHeight = 100;
			} else if (filePath.endsWith("_m135.jpg")) {
				width = ImageUtils.main135ImgWidth;
				height = ImageUtils.main135ImgLen;
				bb = true;
				pressImage = false;
				limitFileSize = 30 * 1024;
				limitImgWidth = 135;
				limitImgHeight = 135;
			} else if (filePath.endsWith("_m250.jpg")) {
				width = ImageUtils.main250ImgWidth;
				height = ImageUtils.main250ImgLen;
				bb = true;
				limitFileSize = 40 * 1024;
				limitImgWidth = 250;
				limitImgHeight = 250;
			} else if (filePath.endsWith("_m400.jpg")) {
				width = ImageUtils.main400ImgWidth;
				height = ImageUtils.main400ImgLen;
				bb = true;
				limitFileSize = 100 * 1024;
				limitImgWidth = 400;
				limitImgHeight = 400;
			} else if (filePath.endsWith("_m500.jpg")) {
				width = ImageUtils.main500ImgWidth;
				height = ImageUtils.main500ImgLen;
				bb = true;
				limitFileSize = 120 * 1024;
				limitImgWidth = 500;
				limitImgHeight = 500;
			}
			// 主图替换检查
			if (thisFileSize > limitFileSize) {
				isPass = false;
				mainFileSize = false;
				mainFileSizeMsg = "档案太大〔大小： " + limitFileSize / 8 + " kb] ";
			}
			if (thisImgHeight != limitImgHeight || thisImgWidth != limitImgWidth) {
				isPass = false;
				mainImgSize = false;
				mainImgSizeMsg = "尺寸不符〔原始尺寸： " + thisImgHeight + " ｘ " + thisImgWidth + "〕 ";
			}
			if (mainFileSize == false || mainImgSize == false) {
				msg = image.getImgFilePath() + " : ";
				if (!mainFileSize) {
					msg = msg + mainFileSizeMsg;
				}
				if (!mainImgSize) {
					msg = msg + mainImgSizeMsg;
				}
			}
		} else if (IMG_TYPE.RMAIN.getValue().equalsIgnoreCase(image.getType())) {
			String mainFileSizeMsg = "";
			String mainImgSizeMsg = "";
			if (filePath.endsWith("_rm93.jpg")) {
				width = ImageUtils.rmain70ImgWidth;
				height = ImageUtils.rmain93ImgLen;
				bb = true;
				pressImage = false;
				limitFileSize = 8 * 1024;
				limitImgWidth = 70;
				limitImgHeight = 93;
			} else if (filePath.endsWith("_rm130.jpg")) {
				width = ImageUtils.rmain100ImgWidth;
				height = ImageUtils.rmain130ImgLen;
				bb = true;
				pressImage = false;
				limitFileSize = 10 * 1024;
				limitImgWidth = 100;
				limitImgHeight = 130;
			} else if (filePath.endsWith("_rm180.jpg")) {
				width = ImageUtils.rmain135ImgWidth;
				height = ImageUtils.rmain180ImgLen;
				bb = true;
				pressImage = false;
				limitFileSize = 16 * 1024;
				limitImgWidth = 135;
				limitImgHeight = 180;
			} else if (filePath.endsWith("_rm225.jpg")) {
				width = ImageUtils.rmain170ImgWidth;
				height = ImageUtils.rmain225ImgLen;
				bb = true;
				pressImage = false;
				limitFileSize = 30 * 1024;
				limitImgWidth = 170;
				limitImgHeight = 225;
			} else if (filePath.endsWith("_rm330.jpg")) {
				width = ImageUtils.rmain250ImgWidth;
				height = ImageUtils.rmain330ImgLen;
				bb = true;
				limitFileSize = 40 * 1024;
				limitImgWidth = 250;
				limitImgHeight = 330;
			} else if (filePath.endsWith("_rm530.jpg")) {
				width = ImageUtils.rmain400ImgWidth;
				height = ImageUtils.rmain530ImgLen;
				bb = true;
				limitFileSize = 100 * 1024;
				limitImgWidth = 400;
				limitImgHeight = 530;
			}
			// 主图替换检查
			if (thisFileSize > limitFileSize) {
				isPass = false;
				mainFileSize = false;
				mainFileSizeMsg = "档案太大〔大小： " + limitFileSize / 8 + " kb] ";
			}
			if (thisImgHeight != limitImgHeight || thisImgWidth != limitImgWidth) {
				isPass = false;
				mainImgSize = false;
				mainImgSizeMsg = "尺寸不符〔原始尺寸： " + thisImgHeight + " ｘ " + thisImgWidth + "〕 ";
			}
			if (mainFileSize == false || mainImgSize == false) {
				msg = image.getImgFilePath() + " : ";
				if (!mainFileSize) {
					msg = msg + mainFileSizeMsg;
				}
				if (!mainImgSize) {
					msg = msg + mainImgSizeMsg;
				}
			}
		} else if (IMG_TYPE.DESC.getValue().equalsIgnoreCase(image.getType())) {
			width = ImageUtils.descBigImgWidth;
			height = bufferedImage.getHeight();
			limitImgWidth = 700;
			bb = false;
			pressImage = false;
			String descImgSizeMsg = "";
			bb = true;
			if (thisImgWidth > limitImgWidth) {
				isPass = false;
				mainImgSize = false;
				descImgSizeMsg = "尺寸不符〔宽度超过： " + limitImgWidth + " px 〕 ";
			}
			if (mainImgSize == false) {
				msg = image.getImgFilePath() + " : ";
				if (!mainImgSize) {
					msg = msg + descImgSizeMsg;
				}
			}
		} else if (IMG_TYPE.IMGB.getValue().equalsIgnoreCase(image.getType())) {
			width = ImageUtils.productBigWidth;
			height = ImageUtils.productBigLen;
			limitImgWidth = 520;
			limitImgHeight = 620;
			String productBigImgSizeMsg = "";
			bb = true;
			if (thisImgHeight > limitImgHeight || thisImgWidth != limitImgWidth) {
				isPass = false;
				mainImgSize = false;
				productBigImgSizeMsg = "尺寸不符,图片宽度必须为520px，高度不超过620px〔原始尺寸： " + thisImgHeight + " ｘ " + thisImgWidth + "〕 ";
			}
			if (mainImgSize == false) {
				msg = image.getImgFilePath() + " : ";
				if (!mainImgSize) {
					msg = msg + productBigImgSizeMsg;
				}
			}
		}
		if (!isPass) {
			throw new CoreException(msg);
		} else {
			if (IMG_TYPE.MAIN.getValue().equalsIgnoreCase(image.getType())) {
				// upload img file
				StringBuffer imgFilePath = new StringBuffer();
				imgFilePath.append(ServerValue.getMidApachePath()).append("PImg").append(File.separator);
				try {
					is = new FileInputStream(file);
					os = new FileOutputStream(imgFilePath.append(image.getProductId().substring(0, 4)).append(File.separator)
							.append(image.getProductId()).append(File.separator).append(image.getProductId()).append("_m").append(
									height).append(".jpg").toString());
					byte buf[] = new byte[1024];
					int len;
					while ((len = is.read(buf)) > 0) {
						os.write(buf, 0, len);
					}
					os.close();
					is.close();
					imgFilePath.setLength(0);
				} catch (FileNotFoundException e) {
					throw new CoreException(e.toString());
				} catch (IOException e) {
					throw new CoreException(e.toString());
				}
			} else if (IMG_TYPE.RMAIN.getValue().equalsIgnoreCase(image.getType())) {
				// upload img file
				StringBuffer imgFilePath = new StringBuffer();
				imgFilePath.append(ServerValue.getMidApachePath()).append("PImg").append(File.separator);
				try {
					is = new FileInputStream(file);
					os = new FileOutputStream(imgFilePath.append(image.getProductId().substring(0, 4)).append(File.separator)
							.append(image.getProductId()).append(File.separator).append(image.getProductId()).append("_rm").append(
									height).append(".jpg").toString());
					byte buf[] = new byte[1024];
					int len;
					while ((len = is.read(buf)) > 0) {
						os.write(buf, 0, len);
					}
					os.close();
					is.close();
					imgFilePath.setLength(0);
				} catch (FileNotFoundException e) {
					throw new CoreException(e.toString());
				} catch (IOException e) {
					throw new CoreException(e.toString());
				}
			} else {
				if (IMG_TYPE.IMGB.getValue().equalsIgnoreCase(image.getType())) {
					ImageUtils.customChange(ImageUtils.productBigWidth, ImageUtils.productBigLen, bb, bufferedImage, ServerValue
							.getMidApachePath()
							+ image.getImgFilePath().substring(1, image.getImgFilePath().length() - 5) + "b.jpg", pressImage);
					ImageUtils.customChange(ImageUtils.productSmallWidth, ImageUtils.productSmallLen, bb, bufferedImage,
							ServerValue.getMidApachePath() + image.getImgFilePath().substring(1, image.getImgFilePath().length() - 5)
									+ "s.jpg", pressImage);
				} else {
					ImageUtils.customChange(width, height, bb, bufferedImage, ServerValue.getMidApachePath()
							+ image.getImgFilePath().substring(1), pressImage);
				}
			}
		}
	}

	public String chkFileSize(String type, List<File> files, List<String> fileNamesList) throws IOException {
		BufferedImage bi = null;
		int thisImgHeight = 0;
		int thisImgWidth = 0;
		int i = 0;
		StringBuffer descImgSizeMsg = new StringBuffer();
		StringBuffer imgbImgSizeMsg = new StringBuffer();
		if (IMG_TYPE.DESC.getValue().equals(type)) {
			int limitImgWidth = ImageUtils.descBigImgWidth;
			i = 0;
			for (File file : files) {
				bi = ImageIO.read(file);
				thisImgWidth = bi.getWidth();
				if (thisImgWidth > limitImgWidth) {
					descImgSizeMsg.append(fileNamesList.get(i)).append(" : 尺寸不符〔宽度超过： ").append(limitImgWidth).append(" px 〕")
							.append("<br/>");
				}
				i++;
			}
		}
		if (IMG_TYPE.PRDT.getValue().equals(type)) {
			int limitImgWidth = ImageUtils.productBigWidth;
			int limitImgHeight = ImageUtils.productBigLen;
			i = 0;
			for (File file : files) {
				bi = ImageIO.read(file);
				thisImgWidth = bi.getWidth();
				thisImgHeight = bi.getHeight();
				if (thisImgWidth != limitImgWidth || thisImgHeight > limitImgHeight) {
					imgbImgSizeMsg.append(fileNamesList.get(i)).append(" : 尺寸不符,图片宽度必须为520px，高度不超过620px〔原始尺寸： ").append(
							thisImgWidth).append(" ｘ ").append(thisImgHeight).append("〕 ").append("<br/>");
				}
				i++;
			}

		}
		String fileTypeMsg = "";
		if (descImgSizeMsg.length() > 0) {
			fileTypeMsg = descImgSizeMsg.toString();
		}
		if (imgbImgSizeMsg.length() > 0) {
			fileTypeMsg = imgbImgSizeMsg.toString();
		}
		return fileTypeMsg;
	}

	/**
	 * 建立新的image entity
	 * 
	 * @param productId
	 * @param type
	 * @param filePath
	 * @param showSeq
	 * @param mainSpecId
	 * @param desc
	 * @param parentId
	 * @return
	 */
	Image createImage(String productId, String type, String filePath, int showSeq, Long mainSpecId, String desc,
			Long parentId) {
		Image image = new Image();
		image.setImgFilePath(filePath);
		image.setProductId(productId);
		image.setShowSeq(showSeq);
		image.setType(type);
		image.setIsDelete("N");
		if (null != mainSpecId && 0 != mainSpecId) {
			image.setMainSpecId(mainSpecId);
		}
		if (null != parentId && 0 != parentId) {
			image.setParentId(parentId);
		}
		if (StringUtils.isNotBlank(desc)) {
			image.setPicDesc(desc);
		}
		return image;
	}
}